package com.fh.controller.system.title;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.fh.controller.base.BaseController;
import com.fh.entity.Page;
import com.fh.entity.system.Role;
import com.fh.util.AppUtil;
import com.fh.util.FileDownload;
import com.fh.util.FileUpload;
import com.fh.util.GetPinyin;
import com.fh.util.ObjectExcelRead;
import com.fh.util.ObjectExcelView;
import com.fh.util.Const;
import com.fh.util.PageData;
import com.fh.util.PathUtil;
import com.fh.util.Tools;
import com.fh.util.Jurisdiction;
import com.fh.service.system.dictionaries.DictionariesService;
import com.fh.service.system.role.RoleService;
import com.fh.service.system.supervisor.SupervisorService;
import com.fh.service.system.title.TitleService;
import com.sun.xml.internal.fastinfoset.stax.events.Util;

/** 
 * 类名称：TitleController
 * 创建人：FH 
 * 创建时间：2015-07-30
 */
@Controller
@RequestMapping(value="/title")
public class TitleController extends BaseController {
	
	String menuUrl = "title/list.do"; //菜单地址(权限用)
	@Resource(name="titleService")
	private TitleService titleService;
	
	@Resource(name="roleService")
	private RoleService roleService;
	
	
	@Resource(name="dictionariesService")
	private DictionariesService dictionariesService;

	@Resource(name="supervisorService")
	private SupervisorService supervisorService;
	
	/**
	 * 新增
	 */
	@RequestMapping(value="/save")
	public ModelAndView save() throws Exception{
		logBefore(logger, "新增Title");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "add")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		
		PageData pd = new PageData();
		
		pd = this.getPageData();
		pd.put("TITLE_ID", this.get32UUID());	//主键
	
		titleService.save(pd);
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	 * 删除
	 */
	@RequestMapping(value="/delete")
	public void delete(PrintWriter out){
		logBefore(logger, "删除Title");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "del")){return;} //校验权限
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			titleService.delete(pd);
			out.write("success");
			out.close();
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
	}
	
	/**
	 * 修改
	 */
	@RequestMapping(value="/edit")
	public ModelAndView edit() throws Exception{
		logBefore(logger, "修改Title");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		titleService.edit(pd);
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	 * 列表
	 */
	@RequestMapping(value="/list")
	public ModelAndView list(Page page){
		logBefore(logger, "列表Title");
		//if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			page.setPd(pd);
			List<PageData>	varList = titleService.list(page);	//列出Title列表
			/*for (PageData pageData : varList) {
				if (Util.isEmptyString(pageData.getString("DEPARTMENT_XI"))) {
				} else {
					PageData pdp = new PageData();
					pdp.put("BIANMA", pageData.getString("DEPARTMENT_XI"));
					String DEPARTMENT_NAME = dictionariesService.findByBM(pdp).getString("NAME");
					pageData.put("DEPARTMENT_XI", DEPARTMENT_NAME);
				}
			}
*/
			System.out.println("varList = [" + varList + "]");
			mv.setViewName("system/title/title_list");
			mv.addObject("varList", varList);
			mv.addObject("pd", pd);
			Map<String, String> hc = this.getHC();
			hc.put("cha", "1");
			hc.put("edit", "1");
			mv.addObject(Const.SESSION_QX, hc);    //按钮权限
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**
	 * 去新增页面
	 */
	@RequestMapping(value="/goAdd")
	public ModelAndView goAdd(){
		logBefore(logger, "去新增Title页面");
		ModelAndView mv = this.getModelAndView();
		
		//pd = this.getPageData();
		try {
			PageData pd = new PageData();
			pd.put("P_BM", "YX");
			List<PageData> roleList = dictionariesService.dictlistPagebyp_bm(pd);
			mv.addObject("roleList", roleList);
			mv.setViewName("system/title/title_edit");
			mv.addObject("msg", "save");
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	
	/**
	 * 去修改页面
	 */
	@RequestMapping(value="/goEdit")
	public ModelAndView goEdit(){
		logBefore(logger, "去修改Title页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
		
			PageData pdp = new PageData();
			pdp.put("P_BM", "YX");
			List<PageData> roleList = dictionariesService.dictlistPagebyp_bm(pdp);
			mv.addObject("roleList", roleList);
			System.out.println("pd1" + pd);
			pd = titleService.findById(pd);	//根据ID读取
			System.out.println("pd2"+pd);
			mv.setViewName("system/title/title_edit");
			mv.addObject("msg", "edit");
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	
	/**
	 * 批量删除
	 */
	@RequestMapping(value="/deleteAll")
	@ResponseBody
	public Object deleteAll() {
		logBefore(logger, "批量删除Title");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "dell")){return null;} //校验权限
		PageData pd = new PageData();		
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			pd = this.getPageData();
			List<PageData> pdList = new ArrayList<PageData>();
			String DATA_IDS = pd.getString("DATA_IDS");
			if(null != DATA_IDS && !"".equals(DATA_IDS)){
				String ArrayDATA_IDS[] = DATA_IDS.split(",");
				titleService.deleteAll(ArrayDATA_IDS);
				pd.put("msg", "ok");
			}else{
				pd.put("msg", "no");
			}
			pdList.add(pd);
			map.put("list", pdList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
		return AppUtil.returnObject(pd, map);
	}
	
	/*
	 * 导出到excel
	 * @return
	 */
	@RequestMapping(value="/excel")
	public ModelAndView exportExcel(){
		logBefore(logger, "导出Title到excel");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;}
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try{
			Map<String,Object> dataMap = new HashMap<String,Object>();
			List<String> titles = new ArrayList<String>();
			titles.add("题目");	//1
			titles.add("题目要求");	//2
			titles.add("课题类型方求向");	//3
			titles.add("课题来源");	//4
			titles.add("限选 系");	//5
			titles.add("限选 本专科");	//6
			titles.add("出题导师姓名");	//7
			titles.add("限选人数");	//8
			titles.add("实际选人数");	//9
			titles.add("题目状态   是否已删除");	//10
			titles.add("导师联系电话号码");	//11
			titles.add("0不需要确认   1:需要双向确认");	//12
			
			
			dataMap.put("titles", titles);
			List<PageData> varOList = titleService.listAll(pd);
			List<PageData> varList = new ArrayList<PageData>();
			for(int i=0;i<varOList.size();i++){
				PageData vpd = new PageData();
				//vpd.put("var0", varOList.get(i).getString("TITLE_ID"));
				vpd.put("var1", varOList.get(i).getString("TITLE_NAME"));	//1
				vpd.put("var2", varOList.get(i).getString("YAOQIU"));	//2
				vpd.put("var3", varOList.get(i).getString("FANGXIANG"));	//3
				vpd.put("var4", varOList.get(i).getString("LAIYUAN"));	//4
				vpd.put("var5", varOList.get(i).getString("DEPARTMENT_XI"));	//5
				vpd.put("var6", varOList.get(i).getString("XIANXUAN"));	//6
				vpd.put("var7", varOList.get(i).getString("SUPERVISOR"));	//7
				vpd.put("var8", varOList.get(i).getString("MAXNUMBER"));	//8
				vpd.put("var9", varOList.get(i).getString("CURRENTNUMBER"));	//9
				vpd.put("var10", varOList.get(i).getString("STATE"));	//10
				vpd.put("var11", varOList.get(i).getString("TELPHONE"));	//11
				vpd.put("var12", varOList.get(i).getString("IS_AFFIRM"));	//12
				/*vpd.put("var13", varOList.get(i).getString("QQ"));	//13
				vpd.put("var14", varOList.get(i).getString("EMAIL"));	//14
				vpd.put("var15", varOList.get(i).getString("INTRODUCE"));	//14
				vpd.put("var16", varOList.get(i).getString("EDUCATION"));	//14

				vpd.put("var17", varOList.get(i).getString("TECHNICAL"));	//14
				vpd.put("var18", varOList.get(i).getString("S_MAXNUMBER"));	//8
				vpd.put("var19", varOList.get(i).getString("S_CURRENTNUMBER"));*/

				varList.add(vpd);
			}
			dataMap.put("varList", varList);
			ObjectExcelView erv = new ObjectExcelView();
			mv = new ModelAndView(erv,dataMap);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**
	 * 打开上传EXCEL页面
	 */
	@RequestMapping(value="/goUploadExcel")
	public ModelAndView goUploadExcel()throws Exception{
		ModelAndView mv = this.getModelAndView();
		try {
			PageData pd = new PageData();
			pd.put("P_BM", "YX");
			List<PageData> roleList1 = dictionariesService.dictlistPagebyp_bm(pd);
			mv.addObject("roleList1", roleList1);
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		mv.setViewName("system/title/uploadexcel");
		return mv;
	}
	
	/**
	 * 下载模版
	 */
	@RequestMapping(value="/downExcel")
	public void downExcel(HttpServletResponse response)throws Exception{
		FileDownload.fileDownload(response, PathUtil.getClasspath() + Const.FILEDOWNPATH + "Title.xls", "Title.xls");
	}
	
	/**
	 * 从EXCEL导入到数据库
	 * @param request 
	 */
	@RequestMapping(value="/readExcel")
	public ModelAndView readExcel(
			@RequestParam(value="excel",required=false) MultipartFile file, HttpServletRequest request
			) throws Exception{
		//System.out.println("excel1");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		int failCount=0;
		int successCount=0;
		int failCounte=0;
		int successCounte=0;
		//System.out.println("excel2");
		if (null != file && !file.isEmpty()) {
			String filePath = PathUtil.getClasspath() + Const.FILEPATHFILE;								//文件上传路径
			String fileName =  FileUpload.fileUp(file, filePath, "titleexcel");							//执行上传
			
			List<PageData> listPd = (List)ObjectExcelRead.readExcel(filePath, fileName, 1, 1, 0);	//执行读EXCEL操作,读出的数据导入List 1:从第2行开始；0:从第A列开始；0:第0个sheet
			
			String DEPARTMENT_XI = request.getParameter("DEPARTMENT_XI");
			String OVERLAP = request.getParameter("OVERLAP");
			/*存入数据库操作======================================*/
			/*pd.put("RIGHTS", "");					//权限
			pd.put("LAST_LOGIN", "");				//最后登录时间
			pd.put("IP", "");						//IP
			pd.put("STATUS", "0");					//状态
			pd.put("SKIN", "default");				//默认皮肤
			
			List<Role> roleList = roleService.listAllERRoles();	//列出所有二级角色
			
			pd.put("ROLE_ID", roleList.get(0).getROLE_ID());*/	//设置角色ID为随便第一个
			/**
			 * var0:序号
			 * var1:题目	
			 * var2 :题目要求	
			 * var3:课题类型方求向	
			 * var4:课题来源	
			 * var5:限选 系	
			 * var6:限选 本专科	
			 * var7:出题导师姓名 	
			 * var8:限选人数	
			 * var9:实际选人数
			 * var10:题目状态   是否已删除
			 * var11:导师联系电话号码
			 * var12:0不需要确认   1:需要双向确认
			 * var13:导师QQ号码
			 * var14:导师电子邮箱
			 * var15:导师简介
			 * var16:导师学历
			 * var17:导师职称
			 * var18:导师限选人数
			 * var19:导师实际人数
			 
			  */
			for(int i=0;i<listPd.size();i++){		
				pd.put("TITLE_ID", this.get32UUID());										//ID
				pd.put("TITLE_NAME", listPd.get(i).getString("var1"));							//姓名
				
				pd.put("YAOQIU", listPd.get(i).getString("var2"));							//编号已存在就跳过
				pd.put("FANGXIANG", listPd.get(i).getString("var3"));
				pd.put("LAIYUAN", listPd.get(i).getString("var4"));
				pd.put("DEPARTMENT_XI", DEPARTMENT_XI);
				pd.put("XIANXUAN", listPd.get(i).getString("var6"));
				pd.put("SUPERVISOR", listPd.get(i).getString("var7"));
				pd.put("MAXNUMBER", listPd.get(i).getString("var8"));
				pd.put("CURRENTNUMBER", listPd.get(i).getString("var9"));
				pd.put("STATE", listPd.get(i).getString("var10"));
				pd.put("TELPHONE", listPd.get(i).getString("var11"));
				pd.put("IS_AFFIRM", listPd.get(i).getString("var12"));
				pd.put("QQ", listPd.get(i).getString("var13"));
				pd.put("EMAIL", listPd.get(i).getString("var14"));
				pd.put("INTRODUCE", listPd.get(i).getString("var15"));
				pd.put("EDUCATION", listPd.get(i).getString("var16"));
				pd.put("TECHNICAL", listPd.get(i).getString("var17"));
				pd.put("S_MAXNUMBER", listPd.get(i).getString("var18"));
				pd.put("S_CURRENTNUMBER", listPd.get(i).getString("var19"));

				//相同数据
				if(titleService.checkthesis(pd) != null) {                                        //判断题目是否重复
					//允许覆盖
					if (OVERLAP.equals("true")) {                        
						titleService.editByTitle_name(pd);               //更新
						//titleService.editBySupervisor(pd);
						//System.out.println("excel3");
						successCount++;
						
					} 
					else //不允许覆盖
					{
						failCount++;
						
					}

				}
				//不同数据
				else  
				{
					titleService.save(pd);
					successCount++;
				}

				
				PageData pdh=new PageData();
				pdh.put("SUPERVISOR_ID", this.get32UUID());
				pdh.put("XIANXUAN", listPd.get(i).getString("var6"));
				pdh.put("SUPERVISOR", listPd.get(i).getString("var7"));
				//pdh.put("MAXNUMBER", listPd.get(i).getString("var8"));
				//pdh.put("CURRENTNUMBER", listPd.get(i).getString("var9"));
				pdh.put("DEPARTMENT_XI", DEPARTMENT_XI);
				pdh.put("TELPHONE", listPd.get(i).getString("var11"));
				pdh.put("QQ", listPd.get(i).getString("var13"));
				pdh.put("EMAIL", listPd.get(i).getString("var14"));
				pdh.put("INTRODUCE", listPd.get(i).getString("var15"));
				pdh.put("EDUCATION", listPd.get(i).getString("var16"));
				pdh.put("TECHNICAL", listPd.get(i).getString("var17"));
				pdh.put("S_MAXNUMBER", listPd.get(i).getString("var18"));
				pdh.put("S_CURRENTNUMBER", listPd.get(i).getString("var19"));
				if(supervisorService.checkedthesis(pd) != null) {                                        //判断题目是否重复
					//允许覆盖
					if (OVERLAP.equals("true")) {                        
						supervisorService.editChecked(pd);               //更新
						//titleService.editBySupervisor(pd);
						//System.out.println("excel3");
						successCounte++;
						
					} 
					else //不允许覆盖
					{
						failCounte++;
						
					}

				}
				//不同数据
				else  
				{
					supervisorService.saveh(pdh);
					successCounte++;
				}
				
			}
			/*存入数据库操作======================================*/
			System.out.println("successCont = [" + successCount + "], failCount = [" + failCount + "]");		
			mv.addObject("msg","success");
		}
		
		Page page=new Page();
		try{
			pd = this.getPageData();
			page.setPd(pd);
			List<PageData>	varList = titleService.list(page);	//列出Title列表
			/*for (PageData pageData : varList) {
				if (Util.isEmptyString(pageData.getString("DEPARTMENT_XI"))) {
				} else {
					PageData pdp = new PageData();
					pdp.put("NAME", pageData.getString("DEPARTMENT_XI"));
				}

			}*/

			mv.setViewName("system/title/uploadexcel");
			mv.addObject("successCount", successCount);
			mv.addObject("failCount", failCount);
			mv.addObject("successCounte", successCounte);
			mv.addObject("failCounte", failCounte);
			
			System.out.println("successCount = [" + successCount + "], failCount = [" + failCount + "]");
			System.out.println("successCounte = [" + successCounte + "], failCounte = [" + failCounte + "]");

			mv.addObject("varList", varList);
			mv.addObject("pd", pd);
			mv.addObject(Const.SESSION_QX,this.getHC());	//按钮权限
		} catch(Exception e){
			logger.error(e.toString(), e);
		
			
			
		}


			
	
		
		//mv.setViewName("save_result");
		return mv;
	}
	
	/* ===============================权限================================== */
	public Map<String, String> getHC(){
		Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
		Session session = currentUser.getSession();
		return (Map<String, String>)session.getAttribute(Const.SESSION_QX);
	}
	/* ===============================权限================================== */
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));
	}
}
